#!coding:utf-8
import netaddr

from rest_framework.response import Response
from rest_framework import status

from cvirt.manager.views import NamedAPIViewMixIn, BaseRetriveAPIView, NonModelBaseAPIView
from cvirt.manager.models import FixedIp, Network, Server
from cvirt.manager.serializers import FixedIpSerializer
from cvirt.common import translate as _

class FixedipList(NamedAPIViewMixIn, NonModelBaseAPIView):
    serializer_class = FixedIpSerializer

    def _get(self,request,*args,**kwargs):

        networkId = request.GET.get("id", "")

        network = Network.objects.get(id=networkId)

        dataset = FixedIp.objects.filter(network=network)
        result = self.paginate(request, dataset, FixedIpSerializer)
        return Response(result)

    def delete_all(self, request, *args, **kwargs):

        ids = request.DATA.get('ids')
        networkId = request.DATA.get('networkid')
        network = Network.objects.get(id=networkId)

        ipnumbers = FixedIp.objects.filter(network=network).count()
        hostnumbers = Server.objects.filter(cluster=network.cluster).count()
        if ipnumbers - len(ids) < hostnumbers:
            return Response(_('剩余的ip数据不能小于集群中的主机数量'),status.HTTP_400_BAD_REQUEST)

        for id in ids:
            ip = FixedIp.objects.get_or_none(id=id)
            if ip: ip.delete()

        dataset = FixedIp.objects.filter(network=network)

        if len(dataset) > 0:
            dhcp_start, dhcp_end = dataset[0].address, dataset[0].address
        else:
            dhcp_start, dhcp_end = "", ""

        for fixedip in dataset:

            if netaddr.IPAddress(fixedip.address) < netaddr.IPAddress(dhcp_start):
                dhcp_start = fixedip.address
            if netaddr.IPAddress(fixedip.address) > netaddr.IPAddress(dhcp_end):
                dhcp_end = fixedip.address

        # 更新网络的dhcp开始和结束
        network.update(dict(dhcp_start=dhcp_start, dhcp_end=dhcp_end))

        return Response(dict(dhcp_start=dhcp_start,dhcp_end=dhcp_end))

class FixedipInfo(NamedAPIViewMixIn, BaseRetriveAPIView):
    serializer_class = FixedIpSerializer

    def create(self, request, *args, **kwargs):

        start = request.DATA.get("start", "")
        end = request.DATA.get("end", "")
        address = request.DATA.get("address", "")
        networkId = request.DATA.get("network_id", "")

        network = Network.objects.get(id=networkId)
        ipnetwork = netaddr.IPNetwork(network.cidr)
        dhcp_start, dhcp_end = network.dhcp_start, network.dhcp_end
        count = 0
        fixedips = []

        if address == "":
            startIp = netaddr.IPAddress(start)
            endIp = netaddr.IPAddress(end)

            #检查是否在掩码范围内
            if startIp not in ipnetwork or endIp not in ipnetwork:
                return Response(_('输入的ip地址不在网络段内'),status.HTTP_400_BAD_REQUEST)

            # 将大的IP作为to
            if startIp > endIp:
                start,end = end,start

            for ip in netaddr.IPRange(start, end):

                try:
                    #避免重复插入数据
                    if not FixedIp.objects.filter(address=str(ip),network=network):
                        fixedip = FixedIp.objects.create(address=str(ip), network=network)
                        fixedips.append(fixedip)
                        count += 1

                        if (not dhcp_start) or (netaddr.IPAddress(dhcp_start) > ip):
                            dhcp_start = str(ip)
                        if (not dhcp_end) or (netaddr.IPAddress(dhcp_end) < ip):
                            dhcp_end = str(ip)
                except Exception as e:
                    return Response(_('添加失败，所添加ip在数据库中存在！'),status.HTTP_400_BAD_REQUEST)
        else:
            try:
                addressIp = netaddr.IPAddress(address)
                #检查是否在掩码范围内
                if addressIp not in ipnetwork:
                    return Response(_('输入的ip地址不在网络段内'),status.HTTP_400_BAD_REQUEST)

                #避免重复插入数据
                if not FixedIp.objects.filter(address=address, network=network):
                    fixedip = FixedIp.objects.create(address=address, network=network)
                    fixedips.append(fixedip)
                    count += 1

                    if (not dhcp_start) or (netaddr.IPAddress(dhcp_start) > netaddr.IPAddress(address)):
                        dhcp_start = address
                    if (not dhcp_end) or (netaddr.IPAddress(dhcp_end) < netaddr.IPAddress(address)):
                        dhcp_end = address

            except Exception as e:
                return Response(_('添加失败，所添加ip在数据库中存在！'),status.HTTP_400_BAD_REQUEST)

        # 更新网络的dhcp开始和结束
        network.update(dict(dhcp_start=dhcp_start, dhcp_end=dhcp_end))

        return Response({'count': count, "data":self.get_serializer(fixedips, many=True).data,
                         'dhcp_start':dhcp_start,'dhcp_end':dhcp_end}, status=200)